package Cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/CookieDome01")
public class CookieDome01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决响应乱码
        resp.setContentType("text/hml;charset=utf-8");

        //获取浏览器自动携带过来的cookie
        Cookie[] cookies = req.getCookies();

        //定义一个变量来接收寻找到的cookie对象
        Cookie c = null;

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                //遍历寻找名称为count的cookie
                if (cookie.getName().equals("count")) {
                    c = cookie;
                }
            }
        }


        //判断c是否还是空
        if (c != null) {
            //找到了名为count的cookie
            //获得浏览器传过来的cookie的值
            String oldValue = c.getValue();
            //旧值加1重新赋值给cookie
            c.setValue(Integer.parseInt(oldValue) + 1 + "");
            if (Integer.parseInt(c.getValue()) <= 3) {
                resp.getWriter().write("欢迎您来访问我们！！！这是您的第" + c.getValue() + "次访问，您还有" + (3 - Integer.parseInt(c.getValue())) + "次访问机会。");

            } else {
                resp.getWriter().write("对不起，您的访问次数已达上限！！！");
            }
        } else {
            //控制浏览器保存一个cookie键值对
            c = new Cookie("count", "1");
        }

        resp.addCookie(c);

    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
